package com.csxh.web.handler.eshop;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.csxh.web.model.eshop.Customer;
import com.csxh.web.service.eshop.CustomerService;
import com.csxh.web.util.servlet.WebUtil;


@Controller
public class UserHandler {

	@Autowired
	private CustomerService customerService;

	@RequestMapping("/userlogin")
	public String showLoginForm() {
		return "userlogin";
	}

	@RequestMapping("/verfcode")
	public void showVerfcode(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "width", defaultValue = "100") int width,
			@RequestParam(value = "height", defaultValue = "40") int height,
			@RequestParam(value = "codeNum", defaultValue = "4") int codeNum) throws IOException {

		WebUtil.buildVerfCodeImage(width, height, codeNum, request, response);

	}

	@RequestMapping("/login")
	public String submitLoginForm(HttpServletRequest request,HttpServletResponse response,
			String username, String password, String verfcode,
			boolean remeberMe) {
		
		//提取成功后重定向的页面
		String redirectPage=WebUtil.getAfterLoginRedirectPage(request);
		System.out.println(redirectPage);		
		// 首先验证图片码
		boolean b = WebUtil.checkVerfCode(verfcode, request);
		if (!b) {
			return "forward:"+WebUtil.buildLoginUrl("/userlogin.action", redirectPage);
		}
		
		// 再次判断用户名与密码
		Customer user = customerService.findBy(username, password);
		if (user == null) {
			return "forward:"+WebUtil.buildLoginUrl("/userlogin.action", redirectPage);
		}
		//将用户对象保存到session中
		WebUtil.setUser(request, user);
		
		//判断是否有记住我
		if(remeberMe){
			WebUtil.rememberMe(request, response, user);
		}
		
		return "redirect:"+redirectPage;

	}
}
